//
//  FreshViewController.m
//  UGoods
//
//  Created by dllo on 16/1/15.
//  Copyright © 2016年 蓝鸥科技.李贺. All rights reserved.
//

#import "FreshViewController.h"
#import "BaseCollectionView.h"
#import "BaseCollectionViewFlowLayout.h"
#import "LHAFNetworkTool.h"
#import "FindModel.h"
#import "GoodsCollectionViewCell.h"
#import "HotSaleCollectionReusableView.h"
#import <MJRefresh.h>
#import "BuyDetailViewController.h"
#import "ConstantsDefine.h"
@interface FreshViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, HotSaleCollectionReusableViewDelegate>

@property (nonatomic, retain) BaseCollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page;

@end

@implementation FreshViewController

- (void)dealloc
{
    Block_release(_buyDetailModelBlock);
    [_collectionView release];
    [_dataArray release];
    [super dealloc];
}

// 数据解析
- (void)handleData {
    NSString *str =[NSString stringWithFormat:@"http://api.ujipin.com/v2/app/ios/phone/v3/list/getNewListData?channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=470825&plantform=iphone&version=314&idx=new&page_size=20&page=%ld", self.page];
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *array = resposeObject[@"data"][@"goods_list"];
        NSMutableArray *mArray = [FindModel modelHandleWithArray:array];
        [self.dataArray addObjectsFromArray:mArray];
       
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        
        if (mArray.count == 0) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
        
        NSLog(@"dataArray:%ld", self.dataArray.count);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败：%@", error);
    }];
}

// 下拉刷新
- (void)addHeaderRefresh {
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self.dataArray removeAllObjects];
        [self handleData];
    }];
    // 设置普通状态的动画图片
    NSArray *idleImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态
    NSArray *pullingImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:pullingImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSInteger i = 0; i < 24; i++) {
        [refreshingImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"loading_%ld", i]]];
    }
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    // 设置所有数据加载完毕的动画图片
    NSArray *NoMoreDataImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:NoMoreDataImages forState:MJRefreshStateNoMoreData];
    
    self.collectionView.mj_header = header;
    
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    // 隐藏状态
    header.stateLabel.hidden = YES;
    
    [self.collectionView.mj_header beginRefreshing];
}

// 上拉加载
- (void)addFooterRefresh {
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page += 1;
        [self handleData];
    }];
}

// 创建CollectionView
- (void)createCollectionView {
    BaseCollectionViewFlowLayout *layout = [[BaseCollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((self.view.frame.size.width - 30 * WIDTH) / 2, 250 * HEIGHT);
    layout.minimumInteritemSpacing = 10 * WIDTH;
    layout.minimumLineSpacing = 10 * HEIGHT;
    layout.sectionInset = UIEdgeInsetsMake(0, 10 * WIDTH, 10 * HEIGHT, 10 * WIDTH);
    layout.headerReferenceSize = CGSizeMake(0, 230 * HEIGHT);

    self.collectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 64 * HEIGHT, self.view.frame.size.width, self.view.frame.size.height - 64 * HEIGHT - 49 * HEIGHT) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor colorWithWhite:0.950 alpha:1.000];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    [_collectionView release];
    [_collectionView registerClass:[GoodsCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [_collectionView registerClass:[HotSaleCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
}

// 创建collectionView的头部
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    HotSaleCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
    headerView.backgroundColor = [UIColor colorWithWhite:0.950 alpha:1.000];
    headerView.delegate = self;
    return headerView;
}

// 头部点击事件
- (void)pushBuyDetailWithModel:(FindModel *)model {
    BuyDetailViewController *buy = [[BuyDetailViewController alloc] init];
    buy.model = model;
    UIViewController *responder = (UIViewController *)self.nextResponder.nextResponder;
    NSLog(@"%@", responder);
    [responder.navigationController pushViewController:buy animated:YES];
    [buy release];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    FindModel *model = self.dataArray[indexPath.item];
    cell.model = model;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    FindModel *model = self.dataArray[indexPath.item];
    self.buyDetailModelBlock(model);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.page = 1;
    self.dataArray = [NSMutableArray array];
    [self handleData];
    [self createCollectionView];
    [self addHeaderRefresh];
    [self addFooterRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
